import json
from flask import Blueprint, request
from utilsapp.common import parsing_data_id
from utilsapp.mysql_con import db_connect

home = Blueprint('home', __name__)

staic_url = ""

@home.route('/getDevice', methods=['POST'])
def home_device():
    scoped = parsing_data_id(request.json['id'], request)
    s0 = f"""select count(*) as num from device where {scoped}"""
    s1 = f"""SELECT COUNT(device_id) as num from (SELECT max(warn_level) as warn_level,device_id from warn WHERE {scoped} and notice=0 and is_show =1
    GROUP BY device_id) k WHERE warn_level =1"""
    s2 = f"""SELECT COUNT(device_id) as num  from (SELECT max(warn_level) as warn_level,device_id from warn WHERE {scoped} and notice=0 and is_show =1
    GROUP BY device_id) k WHERE warn_level =2"""
    s3 = f"""SELECT COUNT(device_id) as num from (SELECT max(warn_level) as warn_level,device_id from warn WHERE {scoped} and notice=0 and is_show =1
    GROUP BY device_id) k WHERE warn_level =3"""
    try:
        result = {
            "msg": "查询成功！",
            "status": 200,
            "data": {
                'all_number': db_connect(s0)["data"][0]["num"],
                'level_one': db_connect(s1)["data"][0]["num"],
                'level_two': db_connect(s2)["data"][0]["num"],
                'level_three': db_connect(s3)["data"][0]["num"]
            }
        }
    except:
        result = {
            "msg": "查询失败！",
            "status": 202
        }
   
    return result


@home.route('/getWarn', methods=['POST'])
def home_warn():
    scoped = parsing_data_id(request.json['id'], request)
    sql = f"""SELECT w.id,w.content as deviceDetail,w.notice as notice,w.device_id,w.sensor_id,s.sensor_name as sensorName,d.device_name as
     deviceName, d.device_img as deviceImg,w.warn_level as warnLevel,w.create_time as create_time from device d, warn w,sensor s WHERE 
     w.device_id = d.id and  w.sensor_id = s.id and  w.{scoped} and w.is_show = 1 and w.notice = 0 ORDER BY 
     w.create_time desc limit 6  """
   
    res = db_connect(sql)
    if res['code'] == 0 and res["data"]:
        for i in res["data"]:
            if i["deviceImg"]:
                if "http" not in i["deviceImg"]:
                    i["deviceImg"] = staic_url + i["deviceImg"][5:]

        result = {
                "msg": "查询成功！",
                "status": 200,
                "data": res["data"]
            }
    else:
        result = {
            "msg": "查询失败！",
            "status": 202
        }

    return result
